/**
 * @author [siwi]
 * @email [siwi@siwi.me]
 * @create date 2017-08-21 07:40:29
 * @modify date 2017-08-21 07:40:29
 * @desc [description]
*/

const Promise = require('bluebird')
const https = require('https')
const { URL } = require('url')
const qs = require('querystring')

module.exports = class Request {
	constructor() {
	}

	/**
	 * get 请求
	 * @param {*请求地址 不带参数} uri 
	 * @param {*请求参数} data 
	 */
	async get(uri, data = {}) {
		return await new Promise((resolve, reject) => {
			let Uri = new URL(uri)
			// 组合search 有search 带? 拼接data 无search  直接拼接data
			let search = `${Uri.search ? Uri.search + '&' : '?'}${qs.stringify(data)}`

			const options = {
				hostname: Uri.hostname,
				path: `${Uri.pathname}${search}`,
				port: Uri.port,
				method: 'GET'
			};

			const req = https.request(options, (res) => {
				if (process.env.NODE_ENV == 'dev') {
					console.log('状态码：', res.statusCode);
					console.log('请求头：', res.headers);
				}
				let body = '';
				res.setEncoding('utf8')
				res.on('data', (chunk) => {
					if (process.env.NODE_ENV == 'dev') {
						process.stdout.write(chunk)
					}
					body += chunk
				});
				res.on('end', function () {
					try {
						let data = JSON.parse(body)
						return resolve(data)
					} catch (err) {
						console.trace(err);
						return reject(err)
					}
				});
			});

			req.on('error', (err) => {
				console.error(err);
				return reject(err)
			});
			req.setTimeout(120000, function () {
				req.abort();
				console.log('Request timeout');
				return false
			});

			req.end();
		}).catch(err => {
			throw new Error(err)
		})
	}

	/**
	 * post请求
	 * @param {*请求地址 不带参数} uri 
	 * @param {*请求参数} data 
	 */
	async post(uri, data) {
		return await new Promise((resolve, reject) => {
			let Uri = new URL(uri)
			const postData = qs.stringify(data);
			const options = {
				hostname: Uri.hostname,
				path: Uri.pathname,
				port: Uri.port,
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Content-Length': Buffer.byteLength(postData)
				}
			};
			const req = https.request(options, (res) => {
				if (process.env.NODE_ENV == 'dev') {
					console.log('状态码：', res.statusCode);
					console.log('请求头：', res.headers);
				}
				let body = ''
				res.setEncoding('utf8')
				res.on('data', (chunk) => {
					if (process.env.NODE_ENV == 'dev') {
						process.stdout.write(chunk)
					}
					body += chunk
				});
				res.on('end', function () {
					try {
						let data = JSON.parse(body)
						return resolve(data)
					} catch (err) {
						console.trace(err);
						return reject(err)
					}
				});
			});

			req.on('error', (err) => {
				console.error(err);
				return reject(err)
			});
			req.setTimeout(120000, function () {
				req.abort();
				console.log('Request timeout');
				return false
			});
			req.write(postData);
			req.end();
		}).catch(err => {
			throw new Error(err)
		})
	}
}
